package com.fdw.smartexam_system.system.controller;


import com.alibaba.fastjson2.JSON;
import com.fdw.smartexam_system.system.model.Question;
import com.fdw.smartexam_system.system.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Autowired
    private OpenAiChatModel chatModel;

    @Autowired
    private QuestionService questionService;

    private final String SysMsg = "你是一个题目生成工具，请根据用户输入的要求生成题目，请严格按照以下JSON格式生成题目数据，包含以下7个核心字段：\n" +
            "{\n" +
            "  \"questionType\": \"题目类型（单选题/多选题/填空题/判断题/简答题/计算题/作文题）\",\n" +
            "  \"questionContent\": \"题目内容描述（含解题必要信息，以markdown形式输出）\",\n" +
            "  \"standardAnswer\": \"标准答案（以markdown形式输出）\",\n" +
            "  \"difficultyLevel\": \"难度值（1-5级，1为最易）\",\n" +
            "  \"knowledgePoint\": [\"知识点路径（如：初中物理/力学/牛顿定律）,\"],\n" +
            "  \"subject\": \"所属学科（如：数学/物理/计算机）\"\n" +
            "}" +
            ",我要用Json解析工具来解析你的生成，请务必要只生成正确的json格式,不要有任何其它东西，如果有公式，请务必用$包裹公式";

    @PostMapping("/create")
    public ResponseEntity<?> createQuestion(@RequestBody Question question) {
        // TODO: 调用服务层方法并返回响应
        Question result = questionService.createQuestion(question);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/ai/generate")
    public ResponseEntity<?> generate(@RequestParam(value = "message") String message) {
        SystemMessage systemMessage = new SystemMessage(SysMsg);
        UserMessage userMessage = new UserMessage(message);
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
        String generation = this.chatModel.call(prompt).getResult().getOutput().getContent();
        System.out.printf(generation);
        Question question = JSON.parseObject(generation, Question.class);
        Question result = questionService.createQuestion(question);
        return ResponseEntity.ok(result);
    }


    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "随便出一个题目") String message) {
        SystemMessage systemMessage = new SystemMessage(SysMsg);
        UserMessage userMessage = new UserMessage(message);
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));
        return this.chatModel.stream(prompt).doOnNext(response -> log.info("AI响应: {}", response.getResult().getOutput().getContent())); // 添加日志;
    }

}
